
struct TreeNode
{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};

#include <algorithm>
#include <unordered_map>
using namespace std;
class Solution
{
public:
    unordered_map<TreeNode *, int> f, g;
    void dfs(TreeNode *root)
    {
        if (f.count(root))
            return;
        int n_max = 0, y_max = root->val;
        if (root->left)
        {
            if (!f.count(root->left))
                dfs(root->left);
            n_max += max(f[root->left], g[root->left]);
            y_max += f[root->left];
        }
        if (root->right)
        {
            if (!f.count(root->right))
                dfs(root->right);
            n_max += max(f[root->right], g[root->right]);
            y_max += f[root->right];
        }
        g[root] = y_max, f[root] = n_max;
        return;
    }
    int rob(TreeNode *root)
    {
        dfs(root);
        return max(f[root], g[root]);
    }
};